package com.ruolin.micro.gateway.server.metadata;


import java.io.Serializable;
import java.util.*;

public class ApplicationRouteMetadata implements Serializable {
    private String application;
    private InstanceMetadata parameters;
    private List<MethodRouteMetadata> methods;
    private List<Type> types;
    private String entityPackage;
    private Map<String, String[]> methodFieldMap = new LinkedHashMap<>();

    public String getApplication() {
        return application;
    }

    public void setApplication(String application) {
        this.application = application;
    }

    public InstanceMetadata getParameters() {
        return parameters;
    }

    public void setParameters(InstanceMetadata parameters) {
        this.parameters = parameters;
    }

    public List<MethodRouteMetadata> getMethods() {
        return methods;
    }

    public void setMethods(List<MethodRouteMetadata> methods) {
        this.methods = methods;
    }

    public List<Type> getTypes() {
        return types;
    }

    public void setTypes(List<Type> types) {
        this.types = types;
    }

    public String getEntityPackage() {
        return entityPackage;
    }

    public void setEntityPackage(String entityPackage) {
        this.entityPackage = entityPackage;
    }

    public Map<String, String[]> getMethodFieldMap() {
        return methodFieldMap;
    }

    public void setMethodFieldMap(Map<String, String[]> methodFieldMap) {
        this.methodFieldMap = methodFieldMap;
    }

    public void init() {
        List<Type> types = getTypes();
        if (types.stream().anyMatch(t -> t.getType().startsWith(entityPackage))) {
            List<MethodRouteMetadata> methods = getMethods();
            for (MethodRouteMetadata method : methods) {
                Optional<Type> optionalType = types.stream().filter(t -> method.getParameterTypes().contains(t.getType())).findFirst();
                if (!method.getParameterTypes().isEmpty()) {
                    Set<String> keySet = optionalType.get().getProperties().keySet();
                    String[] array = keySet.toArray(new String[keySet.size()]);
                    getMethodFieldMap().put(method.getName(), array);
                }

            }
        }
    }

}
